package com.nondo.dean.platform.controller.wap.wechat;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nondo.dean.platform.domain.SignIn;

import com.nondo.dean.platform.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.nondo.dean.common.web.Page;
import com.nondo.dean.common.web.Query;
import com.nondo.dean.common.web.View;
import com.nondo.dean.platform.domain.Coupon;
import com.nondo.dean.platform.domain.Customer;
import com.nondo.dean.platform.domain.Slide;
import com.nondo.dean.platform.model.CustomerBean;
import com.nondo.dean.platform.model.SessionBean;
import com.nondo.dean.platform.model.SlideBean;
import com.nondo.dean.platform.model.WeChatAppLoginReq;
import com.nondo.dean.platform.tool.WeChatConfig;

@Controller("apiWapWeChatMini")
@RequestMapping("/wap/wechat/mini")
public class WeChatMiniController {

    @Autowired
    Environment environment;
    
    @Autowired
    SlideService slideService;
    
    @Autowired
    CouponService couponService;
    
    @Autowired
    CustomerService customerService;

    @Autowired
    WeChatAppMiniService weChatAppMiniService;

    @Autowired
    SignInService signInService;
    
    /**
     * 微信小程序登录
     *
     * @param request
     * @param response
     * @param weChatLoginReq
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public View<SessionBean> weChatLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody WeChatAppLoginReq weChatLoginReq) {
        View<SessionBean> view = new View<SessionBean>(20000, "登录成功");
        // 自定义登录状态
        SessionBean session = weChatAppMiniService.login(weChatLoginReq);
        // 生成用户优惠券
        couponService.generateCouponList(session.getCustomerId());
        view.setData(session);
        return view;
    }
    
    /**
     * 采集用户信息
     * 
     * @param name
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping("/customer/update")
    public View<CustomerBean> updateCustomer(HttpServletRequest request, HttpServletResponse response,
        String sessionId, String name, String phone) {
        View<CustomerBean> view = new View<CustomerBean>(20000, "更新成功");
        SessionBean session = weChatAppMiniService.checkSession(sessionId);
        if (session == null) {
            return View.of401Error("请先登录");
        } else {
            Integer customerId = session.getCustomerId();
            Customer customer = customerService.selectCustomer(customerId);
            customer.setName(name);
            customer.setPhone(phone);
            customerService.updateCustomer(customer);
        }
        return view;
    }
    
    /**
     * 获取优惠券列表
     * @param request
     * @param response
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/list/coupon")
    public View<List<Coupon>> listCoupon(HttpServletRequest request, HttpServletResponse response, String sessionId) {
        View<List<Coupon>> view = new View<List<Coupon>>(20000, "获取列表成功");
        SessionBean session = weChatAppMiniService.checkSession(sessionId);
        if (session == null) {
            return View.of401Error("请先登录");
        }
        Integer customerId = session.getCustomerId();
        List<Coupon> couponList = couponService.getCouponList(customerId);
        
        view.setData(couponList);
        
        return view;
    }
    
    /**
     * 打开活动页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/activity/coupon")
    public ModelAndView goActivityPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("wap/wechat/activity/coupon");
        return mv;
    }
    
    
    /**
     * 核销优惠券
     * @param request
     * @param response
     * @param code 优惠券编码
     * @return
     */
    @ResponseBody
    @RequestMapping("/coupon/verificate")
    public View<Coupon> verificate(HttpServletRequest request, HttpServletResponse response, String sessionId,
        String code) {
        View<Coupon> view = new View<Coupon>(20000, "更新成功");
        SessionBean session = weChatAppMiniService.checkSession(sessionId);
        if (session == null) {
            return View.of401Error("请先登录");
        }
        Coupon couponDb = couponService.selectCouponByCode(code);
        if (couponDb != null) {
            if (!couponDb.getCustomerId().equals(session.getCustomerId())) {
                return View.of401Error("优惠券和登录用户不匹配");
            }
            if (couponDb.getStatus() == 1) {
                return View.of401Error("优惠券已使用");
            }
            couponDb.setStatus(1);
            this.couponService.updateCoupon(couponDb);
        } else {
            return View.of401Error("优惠券不存在");
        }

        return view;
    }
    
    /**
     * 扫一扫下单
     * @return 
     */
    @ResponseBody
    @RequestMapping("/scan/order")
    public View<Integer> placeOrder(HttpServletRequest request, HttpServletResponse response, String sessionId) {
        View<Integer> view = new View<Integer>(20000, "下单成功");
        SessionBean session = weChatAppMiniService.checkSession(sessionId);
        if (session == null) {
            return View.of401Error("请先登录");
        } else {
            Integer customerId = session.getCustomerId();
            Customer customer = customerService.selectCustomer(customerId);
            if ("ADMIN".equals(customer.getRemarks())) {
                return View.of401Error("你的账户没有扫码权限");
            }
            customer.setIsOrder(WeChatConfig.IS_ORDER);
            customerService.updateCustomer(customer);
        }
        return view;
    }
    
    /**
     * 开启和停止摇一摇
     * @param type 操作类型
     * @return 
     */
    @ResponseBody
    @RequestMapping("/shake/opt")
    public View<Integer> startAndStopShake(HttpServletRequest request, HttpServletResponse response, Integer type) {
        View<Integer> view = new View<Integer>(20000, "更新成功");
        if (type == null) {
            return View.ofParamsError("type值不能为空");
        }
        type = weChatAppMiniService.startAndStopShake(type);
        view.setData(type);
        return view;
    }
    
    /**
     * 累计摇动次数
     * @param shakeNum 摇动次数
     * @return 
     */
    @ResponseBody
    @RequestMapping("/shake/add")
    public View<Map<String,Integer>> addShakeNum(HttpServletRequest request, HttpServletResponse response, String sessionId, Integer shakeNum) {
        View<Map<String,Integer>> view = new View<Map<String,Integer>>(20000, "更新成功");
        SessionBean session = weChatAppMiniService.checkSession(sessionId);
        if (session == null) {
            return View.of401Error("请先登录");
        }
        if (shakeNum == null) {
            return View.ofParamsError("摇一摇次数必传");
        }
        Integer customerId = session.getCustomerId();
        Integer shakeStaus = weChatAppMiniService.startAndStopShake(WeChatConfig.GET_SHAKE);
        if (shakeStaus == WeChatConfig.START_SHAKE) {
            shakeNum = weChatAppMiniService.addShakeNum(customerId, shakeNum);
        } else {
            return View.ofParamsError("活动未开始或者已结束");
        }
        Map<String,Integer> resultMap = new HashMap<String, Integer>();
        resultMap.put("shakeStatus", shakeStaus);
        resultMap.put("shakeNum", shakeNum);
        view.setData(resultMap);
        return view;
    }
    
    /**
     * 摇一摇次数排行榜
     * @return 
     */
    @ResponseBody
    @RequestMapping("/shake/list")
    public View<Page<CustomerBean>> rankList(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<Customer> query) {
        View<Page<CustomerBean>> view = new View<Page<CustomerBean>>(20000, "获取列表成功");

        Customer customer = query.getData();

        Page<CustomerBean> page = new Page<CustomerBean>(query.getPage(), query.getSize(), customerService.count(customer));
        
        List<Customer> customerList = customerService.getShakeRankList(query.getOffset(), query.getLimit(), customer);
        
        List<CustomerBean> customerBeanList = new ArrayList<CustomerBean>();
        
        for (Customer customerDb : customerList) {
            CustomerBean customerBean = CustomerBean.covertToBean(customerDb);
            customerBeanList.add(customerBean);
        }
        
        page.setContent(customerBeanList);
        
        view.setData(page);
        
        return view;
    }
    
    /**
     * 打开活动控制页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/activity/control")
    public ModelAndView goControlPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("wap/wechat/activity/control");
        return mv;
    }
    
    /**
     * 打开排行榜页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/activity/rank")
    public ModelAndView goRankListPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("wap/wechat/activity/rank");
        return mv;
    }
    
    /**
     * 查看幻灯片详情
     * @param request
     * @param response
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/slide/info/{id}")
    public View<SlideBean> info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) {
        View<SlideBean> view = new View<SlideBean>(20000, "获取数据成功");
        
        SlideBean slideBean = new SlideBean();
        if (id != null) {
            Slide slide = slideService.selectSlide(id);
            slideBean = slideService.getSlideBean(slide);
        } 

        view.setData(slideBean);
        return view;
    }
    
    /**
     * 获取幻灯片列表
     * @param request
     * @param response
     * @param query
     * @return
     */
    @ResponseBody
    @RequestMapping("/slide/list")
    public View<List<SlideBean>> list(HttpServletRequest request, HttpServletResponse response) {
        View<List<SlideBean>> view = new View<List<SlideBean>>(20000, "获取列表成功");

        List<Slide> slideList = slideService.getSlideList(2);
        
        List<SlideBean> slideBeanList = new ArrayList<SlideBean>();
        
        for (Slide slide : slideList) {
            SlideBean slideBean = slideService.getSlideBean(slide);
            slideBeanList.add(slideBean);
        }
        
        view.setData(slideBeanList);
        
        return view;
    }

    /**
     * 签到
     * @param request
     * @param response
     * @param sessionId
     * @return
     */
    @ResponseBody
    @RequestMapping("/sign/add")
    public View<String> addSignIn(HttpServletRequest request, HttpServletResponse response,String sessionId){
        View<String> view = new View<>(20000,"签到成功");
        SessionBean session = weChatAppMiniService.checkSession(sessionId);
        if (session == null) {
            return View.of401Error("请先登录");
        }
        SignIn signIn = new SignIn();
        signIn.setCustomerId(session.getCustomerId());
        if(signInService.selectExmple(signIn).size()>0){
            return View.ofParamsError("不能重复签到");
        }
        signInService.add(signIn);
        return view;
    }

    /**
     * 签到列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/registration/list")
    public View<Page<CustomerBean>> signList(HttpServletRequest request, HttpServletResponse response) {
        View<Page<CustomerBean>> view = new View<Page<CustomerBean>>(20000, "获取列表成功");
        Query<SignIn> query = new Query<>();
        query.setPage(1);
        query.setSize(500);
        SignIn signIn = query.getData();
        if(signIn==null){
            signIn =new SignIn();
        }

        Page<CustomerBean> page = new Page<CustomerBean>(query.getPage(), query.getSize(), signInService.countDay());

        List<CustomerBean> customerList = signInService.getSignList(query.getOffset(), query.getLimit(), signIn);

        page.setContent(customerList);

        view.setData(page);

        return view;
    }
}